#include "FrameBuffer.h"
#include "ScreenResolution.h"

FrameBuffer::FrameBuffer(void)
{
	m_fboId = 0;
	m_colorId = 0;
	m_depthId = 0;
}

FrameBuffer::~FrameBuffer(void)
{
	glDeleteFramebuffers(1, &m_fboId);
	glDeleteTextures(1, &m_colorId);
	glDeleteTextures(1, &m_depthId);
}

void FrameBuffer::Init()
{
	GLint texWidth = ScreenResolution::GetInstance()->GetScreenWitdh();
	GLint texHeight = ScreenResolution::GetInstance()->GetScreenHeight();

	// generate the framebuffer, & texture object names
	glGenFramebuffers(1, &m_fboId);
	glGenTextures(1, &m_colorId);
	glGenTextures(1, &m_depthId);

	// bind color texture and load the texture mip-level 0
	// texels are RGB565
	// no texels need to specified as we are going to draw into
	// the texture
	glBindTexture(GL_TEXTURE_2D, m_colorId);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glBindTexture(GL_TEXTURE_2D, 0);

	// bind depth texture and load the texture mip-level 0
	// no texels need to specified as we are going to draw into
	// the texture
	glBindTexture(GL_TEXTURE_2D, m_depthId);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, texWidth,
		texHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT,
		NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glBindTexture(GL_TEXTURE_2D, 0);

	// bind the framebuffer
	glBindFramebuffer(GL_FRAMEBUFFER, m_fboId);

	// specify texture as color attachment
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
		GL_TEXTURE_2D, m_colorId, 0);

	// specify texture as depth attachment
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
		GL_TEXTURE_2D, m_depthId, 0);

	GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if (status == GL_FRAMEBUFFER_COMPLETE)
	{
		LOGI("FrameBuffer OK\n");
	}
	else
	{
		LOGI("FrameBuffer is not OK\n");
	}

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

GLuint FrameBuffer::GetFboId()
{
	return m_fboId;
}

GLuint FrameBuffer::GetColorId()
{
	return m_colorId;
}

GLuint FrameBuffer::GetDepthId()
{
	return m_depthId;
}
